package com.qisi.kandroidshalon

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.qisi.kandroidshalon.delegate.CustomDelegate
import com.qisi.kandroidshalon.delegate.CustomPrinter
import com.qisi.kandroidshalon.delegate.DefaultPrinter
import com.qisi.kandroidshalon.permission.PermissionManager
import com.qisi.kandroidshalon.viewmodel.MainViewModel

/**
 * Compose的特点:
 * 1.声明示编程，不需要各种findviewbyid和手动状态管理，由状态驱动ui,我们需要将着重点关注于状态变化的逻辑上即可，可以从大量的ui模版代码中解放出来。
 * 2.另一个强大之处在于“重组”（Recomposition）。当状态发生变化时，Compose会只重新绘制那些受影响的部分，而不是整个界面。这极大地提高了UI更新的效率，也让代码的逻辑更加清晰。
 * 3.因为是可组合的，所以compose函数复用性高
 */
class ComposeBaseDemo : ComponentActivity() {

    private val mainViewModel: MainViewModel by viewModels()


    private val delegate: CustomDelegate = CustomDelegate()

    /**
     * 该属性委托给CustomDelegate对象
     */
    var delegateProp: String by delegate

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        PermissionManager.requestPermissions(this)
        //此处是实现页面沉浸式
        enableEdgeToEdge()
        setContent {
            MyScreen(mainViewModel)
        }


        /**
         * by关键字-CustomPrinter委托接口指责给DefaultPrinter对象
         */
        val customPrinter = CustomPrinter(DefaultPrinter())
        customPrinter.print("hello")

        delegateProp = "hello delegate"
        Log.i("CustomDelegate", delegateProp)
        Log.i("CustomDelegate", "lazy int ${delegate.lazyVal}")

        Log.i("debugTask", "" + taskId)
    }
}

/**
 * @Composable 标记的函数都是没有返回值，只用于描述界面,
 * 此方法表示可以组合界面，只有此标记的方法之间才能调用
 */
@Composable
fun MyScreen(viewModel: MainViewModel) {
//    //可变化的状态mutableState,和ui双向绑定
//    var count by remember {
//        mutableStateOf("hello")
//    }
    //垂直容器
    Column(
        //小括号里是本ui的属性
        //modifier类似布局参数
        modifier = Modifier
            .fillMaxSize()
            .padding(40.dp),
        //水平居中
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        //按钮
        Button(
            //设置点击事件,更改文本
            onClick = { viewModel.count++ }) {
            //大括号里是挂载的子组件
            Text(
                text = "Click Me", color = Color.White
            )
        }
        Text(text = "${viewModel.count}")
        //列表
        TextList(mutableListOf("11", "22", "33"))

        var count by remember { mutableIntStateOf(0) }

        Button(onClick = { count++ }) {
            Text(text = "Click $count times")
        }

        Image(
            //设置方式1
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = "A dog image"
        )

        ImageRow()

        ComplexList()
    }
}

/**
 * 网络图片列表
 */
@Composable
fun ImageRow() {
    LazyRow(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.Gray)
    ) {
        items(9, key = { it }) {
            Log.i("debug", "$it")
            AsyncImage(
                modifier = Modifier
                    .size(60.dp)
                    //切成圆形
                    .clip(CircleShape)
                    //圆形边框
                    .border(3.dp, Color.Blue, CircleShape),
                model = "https://img-blog.csdnimg.cn/20200401094829557.jpg",
                contentDescription = "desc"
            )
        }

    }
}


/**
 * 简单的水平列表
 */
@Composable
fun TextList(messages: List<String>) {
    LazyRow {
        //items函数传入数据和block
        items(messages) { message ->
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .padding(8.dp)
                    .background(Color.Gray),
                //内容居中
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = message
                )
            }
        }
    }
}

@Composable
fun ComplexList() {
    val items = remember { listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6") }

    LazyVerticalGrid(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Yellow),
        //每一行分为两列
        columns = GridCells.Fixed(2),
        verticalArrangement = Arrangement.spacedBy(10.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        //表头
        item(span = { GridItemSpan(2) }) {
            Text(text = "Grid Section")
        }
        //两列，个数四个
        items(count = 4, span = { GridItemSpan(1) }) { index ->
            Text(
                text = "List Item $index",
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(16.dp)
            )
        }
        //  表头
        item(span = { GridItemSpan(2) }) {
            Text(text = "Horizontal Scroll Section")
        }
        // 占用两列
        item(span = { GridItemSpan(2) }) {
            //Row表示横向布局
            LazyRow(
                modifier = Modifier.fillMaxWidth(),
                //item之间的水平间距
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(8.dp)
            ) {
                items(items) { item ->
                    Box(
                        modifier = Modifier
                            .background(MaterialTheme.colorScheme.secondary)
                            .padding(16.dp)
                            .width(120.dp)
                            .height(120.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(text = item, color = Color.White)
                    }
                }
            }
        }
        //表头
        item(span = { GridItemSpan(2) }) {
            Text(text = "Linear Section")
        }
        //垂直列表,一个item占用一整行
        items(count = 3, span = { GridItemSpan(2) }) { index ->
            Text(
                text = "List Item $index",
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(16.dp)
            )
        }

    }
}

//预览
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    MyScreen(viewModel = MainViewModel())
}